import { defineStore } from 'pinia'
import { computed, ref } from 'vue'
import { useCookieStore } from './cookieStore'
import { useUserInfoStore } from './userInfoStore'
import {
  getUserPlayListAPi,
  getUserPlayListAllAPi,
  getRecommentSongListAPi,
  getPersonalizedAPi
} from '@/apis/song'


export const usePlayListStore = defineStore('playList', () => {
  const useUserInfo = useUserInfoStore()
  const useCookie = useCookieStore()

  // 用户的歌单列表（包括创建和收藏的歌单）
  const playList = ref([])
  // 获取用户所有的歌单
  const getUserPlayList = async (id) => {
    const { data } = await getUserPlayListAPi(id)
    const list = data.playlist
    list.forEach(item => item.select = false)
    playList.value = list
  }

  // 从用户所有歌单中，提取我喜欢歌单
  const likeList = computed(() => playList.value[0])

  // 从用户所有歌单中，提取创建的歌单
  const createPlayList = computed(() => {
    return playList.value.filter(item => {
      if (item.creator.userId === useUserInfo.userInfo.account.id) {
        return item
      }
    })
  })

  // 从用户所有歌单中，提取收藏的歌单
  const collectPlayList = computed(() => {
    return playList.value.filter(item => {
      if (item.creator.userId !== useUserInfo.userInfo.account.id) {
        return item
      }
    })
  })

  // 获取我喜欢歌单的内容
  const likeListContent = ref([])
  const getLikeListContent = async () => {
    const { data } = await getUserPlayListAllAPi(likeList.value.id, likeList.value.trackCount, 0)
    likeListContent.value = data.songs
  }

  // 首页推荐歌单，根据登录状态获取不同格式的歌单
  const recommendList = ref([])
  const isShowSkeleton = ref(true)
  const getRecommendList = async () => {
    if (useCookie.cookie.cookie) {
      const { data } = await getRecommentSongListAPi()
      recommendList.value = data.recommend
      isShowSkeleton.value = false
    } else {
      const { data } = await getPersonalizedAPi()
      recommendList.value = data.result
      isShowSkeleton.value = false
    }
  }

  // 清空歌单
  const clearPlayList = () => {
    playList.value = []
  }

  return {
    getUserPlayList,
    getLikeListContent,
    getRecommendList,
    clearPlayList,
    playList,
    createPlayList,
    collectPlayList,
    likeList,
    likeListContent,
    recommendList,
    isShowSkeleton
  }
})
